package com.company.manage.system.web.controller;

import com.company.manage.common.base.BaseController;
import com.company.manage.common.persistence.Page;
import com.company.manage.common.persistence.PropertyFilter;
import com.company.manage.system.entity.Role;
import com.company.manage.system.entity.User;
import com.company.manage.system.service.RolePermissionService;
import com.company.manage.system.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by HuangYong on 2016/1/23.
 * desc:角色controller
 */
@Controller
@RequestMapping("system/role")
public class RoleController extends BaseController {
    private static final String TAG = "RoleController";

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @RequestMapping(method = RequestMethod.GET)
    public String list(){
        return "system/roleList";
    }

    /**
     * 加载角色集合 JSON
     * @param request
     * @return
     */
    @RequestMapping(value = "json",method = RequestMethod.GET)
    @RequiresPermissions("sys:role:view")
    @ResponseBody
    public Map<String,Object> getData(HttpServletRequest request){
        Page<Role> page = getPage(request);
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
        page = roleService.search(page,filters);

        return getEasyUIData(page);
    }

    /**
     * 获取角色拥有的权限id 集合
     *
     * @param id
     * @return
     */
    @RequiresPermissions("sys:role:permView")
    @RequestMapping("{id}/json")
    @ResponseBody
    public List<Integer> getRolePermissions(@PathVariable("id") Integer id){
        List<Integer> permissionIdList = rolePermissionService.getPermissionIds(id);
        return permissionIdList;
    }

    /**
     * 修改角色权限
     * @param id
     * @param newRoleIds
     * @param session
     * @return
     */
    @RequestMapping(value = "{id}/updatePermission")
    @RequiresPermissions("sys:role:permUpd")
    @ResponseBody
    public String updateRolePermission(@PathVariable("id") Integer id, @RequestBody List<Integer> newRoleIds, HttpSession session){
        List<Integer> oldRoleIds = rolePermissionService.getPermissionIds(id);

        /*获取application中的sessions*/
        HashSet sessions = (HashSet) session.getServletContext().getAttribute("sessions");

        Iterator<Session> iterator = sessions.iterator();
        PrincipalCollection pc = null;

        while (iterator.hasNext()){
            HttpSession s = (HttpSession) iterator.next();
            User user = (User) s.getAttribute("user");
            if(user.getId()==id){
                pc = (PrincipalCollection) s.getAttribute(String.valueOf(id));

                /*清除该用户权限缓存*/
                rolePermissionService.clearUserPermissionCache(pc);
                s.removeAttribute(String.valueOf(id));
                break;
            }

        }
        rolePermissionService.updateRolePermission(id,oldRoleIds,newRoleIds);
        return "success";

    }

    /**
     * 添加角色跳转
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:add")
    @RequestMapping(value = "create",method = RequestMethod.GET)
    public String createForm(Model model){
        model.addAttribute("role",new Role());
        model.addAttribute("action","create");

        return "system/roleForm";
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @RequiresPermissions("sys:role:add")
    @RequestMapping(value = "create",method = RequestMethod.POST)
    @ResponseBody
    public String create(@Valid Role role){
        roleService.save(role);
        return "success";
    }

    /**
     * 修改角色跳转
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("sys:role:update")
    @RequestMapping(value = "update/{id}",method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Integer id,Model model){
        model.addAttribute("role",roleService.get(id));
        model.addAttribute("action","update");
        return "system/roleForm";
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @RequiresPermissions("sys:role:update")
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ResponseBody
    public String update(@Valid @ModelAttribute("role") Role role){
        roleService.save(role);
        return "success";
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @RequiresPermissions("sys:role:delete")
    @RequestMapping(value = "delete/{}id",method = RequestMethod.GET)
    @ResponseBody
    public String delete(@PathVariable("id") Integer id){
        roleService.delete(id);
        return "success";
    }

    @ModelAttribute
    public void getRole(@RequestParam(value = "id",defaultValue = "-1") Integer id,Model model){
        if(id!=-1){
            model.addAttribute("role",roleService.get(id));
        }
    }



} 